<?php

namespace App\Http\Controllers\Dynamic;

use App\Models\Dynamic\BloodDiet;
use App\Models\Dynamic\BloodMedication;
use App\Models\Dynamic\BloodMotion;
use App\Models\Dynamic\SamGlucose;
use App\Models\Dynamic\SamReferGlucose;
use App\Models\Dynamic\SamWear;
use App\Models\Dynamic\BloodExcelReport;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\DB;

class SamGlucoseController extends ApiController
{
    /**
     * @var \App\Models\Dynamic\SamGlucose
     */
    protected $samGlucose;
    /**
     * @var \App\Models\Dynamic\SamWear
     */
    protected $samWear;

    protected $user;

    protected $bloodDiet;

    protected $bloodMotion;

    protected $bloodMedication;

    protected $samReferGlucose;

    protected $request;

    /**
     * SamGlucoseController constructor.
     * @param \App\Models\Dynamic\SamGlucose $samGlucose
     * @param \App\Models\Dynamic\SamWear $samWear
     * @param \App\Models\Dynamic\BloodMotion $bloodMotion
     * @param \App\Models\Dynamic\BloodDiet $bloodDiet
     * @param \App\Models\Dynamic\BloodMedication $bloodMedication
     * @param \App\Models\Dynamic\SamReferGlucose $samReferGlucose
     * @param \Illuminate\Http\Request $request
     */
    public function __construct(SamGlucose $samGlucose, Request $request, SamWear $samWear,
                                BloodMotion $bloodMotion, BloodDiet $bloodDiet, BloodMedication $bloodMedication,
                                SamReferGlucose $samReferGlucose, User $user)
    {
        parent::__construct();

        $this->user = $user;
        $this->samGlucose = $samGlucose;
        $this->samWear = $samWear;
        $this->bloodMotion = $bloodMotion;
        $this->bloodDiet = $bloodDiet;
        $this->bloodMedication = $bloodMedication;
        $this->samReferGlucose = $samReferGlucose;
        $this->request = $request;
    }

    /**
     * SamGlucoseController index
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {

        $this->validate($this->request, [
            'start' => 'string',
            'end' => 'string',
            'user_id' => 'required|integer'
        ]);


        $user_id = $this->request->input('user_id');
        $user = $this->user
            ->withoutGlobalScopes()
            ->select('id', 'account')
            ->find($user_id);

        $userId = $user->id;
        $start = $this->request->input('start');
        $end = $this->request->input('end');

        if (empty($start) && empty($end)) {

            $lastSamWear = $this->samWear
                ->whereUserid($userId)
                ->orderBy('id', 'desc')
                ->first();

            if ($lastSamWear) {
                $start = $lastSamWear->starttime;
                $end = $lastSamWear->endtime;
            }
        }
        $data = [];
        //查询当前佩戴设备传递的血糖信息
        $glucose = $this->samGlucose
            ->select(['id', 'value', 'currentvalue', 'collectedtime', 'createdtime',])
            ->whereUserid($userId)
            ->whereBetween('collectedtime', [$start, $end])
            ->get()
            ->toArray();


        $data['glucose'] = $glucose;

        //获取参比
        $referGlucose = $this->samReferGlucose
            ->getListUser($userId, $start, $end)
            ->get()
            ->toArray();
        $data['referGlucose'] = $referGlucose;

        //胰岛素使用情况
        $medicalInfo1 = $this->bloodMedication
            ->getInfoListByUser($userId, $start, $end);
        $data['medicalInfo1'] = $medicalInfo1;

        //用药
        $medicalInfo2 = $this->bloodMedication
            ->getInfoListByUser($userId, $start, $end, 1);
        $data['medicalInfo2'] = $medicalInfo2;

        //饮食
        $diet = $this->bloodDiet->getListUser($userId, $start, $end)
            ->get()
            ->toArray();
        $data['diet'] = $diet;


        //运动
        $motion = $this->bloodMotion->getListUser($userId, $start, $end)
            ->get()
            ->toArray();
        $data['motion'] = $motion;

        return $this->response($data);

    }


    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getListByTimeByUId()
    {

        $this->validate($this->request, [
            'id' => 'required|integer',
            'user_id' => 'required|integer'
        ]);

        $user_id = $this->request->input('user_id');
        $user = $this->user
            ->withoutGlobalScopes()
            ->select('id', 'account')
            ->find($user_id);

        $userId = $user->id;
        $id = $this->request->input('id');

        $lastSamWear = $this->samWear
            ->whereUserid($userId)
            ->whereId($id)
            ->orderBy('id', 'desc')
            ->first();

        if ($lastSamWear) {
            $start = $lastSamWear->starttime;

            $end = $lastSamWear->endtime;
            if (empty($end)) {
                $end = Carbon::now()->toDateTimeString();
            }

        } else {
            $start = "2013-12-31 00:00:00";

            $end = Carbon::now()->toDateTimeString();
        }

        //查询当前佩戴设备传递的血糖信息

        $glucose = $this->samGlucoseF
            ->select(['id', 'value', 'currentvalue', 'collectedtime', 'createdtime'])
            ->whereUserid($userId)
            ->whereBetween('collectedtime', [(string)$start, (string)$end])
            ->orderBy('collectedtime', 'desc')
            ->get()
            ->toArray();

        return $this->response($glucose);
    }


    public function reportPrint()
    {
        $user_id = $this->request->input('user_id');
        $startTime = $this->request->input('startTime');
        $endTime = $this->request->input('endTime');
        $excel_params = [];
        if($report_id = $this->request->input('print_id'))
        {
            $dataInfo =  BloodExcelReport::where('id',$report_id)->first()->toArray();
            $excel_params  = json_decode($dataInfo['excel_params']);
        }
        return view('manage.reportPrint')->with('user_id', $user_id)->with('startTime', $startTime)->with('endTime', $endTime)->with('excel_params',$excel_params);
    }

    /**
     * 添加已经打印的文件的信息(为客户端访问时需要的一些参数做准备)
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function addReportInfo()
    {
        $this->validateInput();
        $addDatas = $this->request->all();
        $addData = [
//            'record_id' => $addDatas['record_id'],
            'user_id' =>$addDatas['user_id'],
            'excel_name' => '随糖动态血糖监测报告'.time().'xls',
            'excel_params'=>json_encode($this->request->input('excel_params')),
            'excel_url'  => $this->request->input('excel_url'),
            'created_at' =>date('Y-m-d',time()),
            'updated_at' =>date('Y-m-d',time()),
        ];
        $result = BloodExcelReport::create($addData);

        return $this->hasData([]);

    }

    /**
     * 验证参数
     */
    protected function validateInput()
    {
        $this->validate($this->request, [
//            'record_id' => 'required',
            'user_id' => 'required',
        ]);
    }
}
